import { defineStore } from 'pinia'
import { userApi } from '../api/user'

export const useUserStore = defineStore('user', {
  state: () => ({
    users: [],
    currentUser: null,
    loading: false,
    error: null
  }),
  
  getters: {
    // 获取活跃用户
    activeUsers: (state) => state.users.filter(user => user.status === 'active'),
    
    // 获取用户总数
    userCount: (state) => state.users.length,
    
    // 根据ID获取用户
    getUserById: (state) => (id) => state.users.find(user => user.id === id)
  },
  
  actions: {
    // 获取所有用户
    async fetchUsers() {
      this.loading = true
      this.error = null
      
      try {
        const response = await userApi.getUsers()
        if (response.success) {
          this.users = response.data
        } else {
          this.error = response.message || '获取用户列表失败'
        }
      } catch (error) {
        this.error = error.message
        console.error('获取用户失败:', error)
      } finally {
        this.loading = false
      }
    },
    
    // 创建用户
    async createUser(userData) {
      this.loading = true
      this.error = null
      
      try {
        const response = await userApi.createUser(userData)
        if (response.success) {
          // 将新用户添加到列表中
          this.users.unshift(response.data)
          return response
        } else {
          this.error = response.message || '创建用户失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 更新用户
    async updateUser(id, userData) {
      this.loading = true
      this.error = null
      
      try {
        const response = await userApi.updateUser(id, userData)
        if (response.success) {
          // 更新本地用户数据
          const index = this.users.findIndex(user => user.id === id)
          if (index !== -1) {
            this.users[index] = { ...this.users[index], ...response.data }
          }
          return response
        } else {
          this.error = response.message || '更新用户失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 删除用户
    async deleteUser(id) {
      this.loading = true
      this.error = null
      
      try {
        const response = await userApi.deleteUser(id)
        if (response.success) {
          // 从列表中移除用户
          this.users = this.users.filter(user => user.id !== id)
          return response
        } else {
          this.error = response.message || '删除用户失败'
          throw new Error(this.error)
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },
    
    // 设置当前用户
    setCurrentUser(user) {
      this.currentUser = user
    },
    
    // 清除错误
    clearError() {
      this.error = null
    }
  }
})


